'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  // 修复：同时支持新旧参数名，确保兼容性
  const { 
    taskId, 
    status, 
    acceptorId, 
    acceptorName, 
    acceptorAvatar,
    receiverId,    // 新增：支持前端传递的参数名
    receiverName,  // 新增：支持前端传递的参数名
    receiverAvatar // 新增：支持前端传递的参数名
  } = event;
  
  console.log('【updateTaskStatus】云函数被调用，event：', event);
  console.log('【updateTaskStatus】参数解析：');
  console.log('  - receiverId:', receiverId);
  console.log('  - receiverName:', receiverName);
  console.log('  - receiverAvatar:', receiverAvatar);
  console.log('  - acceptorId:', acceptorId);
  console.log('  - acceptorName:', acceptorName);
  console.log('  - acceptorAvatar:', acceptorAvatar);
  
  if (!taskId || !status) {
    return { code: 400, msg: 'Missing parameters' };
  }

  try {
    const collection = db.collection('taskList');
    
    // 先获取任务详情，用于生成通知
    const taskRes = await collection.doc(taskId).get();
    if (!taskRes.data || taskRes.data.length === 0) {
      return { code: 404, msg: 'Task not found' };
    }
    
    const task = taskRes.data[0];
    console.log('【updateTaskStatus】任务详情：', task);
    
    const updateData = { 
      status: status, 
      latest_update: new Date().toISOString() 
    };

    // 修复：使用正确的参数名，优先使用新参数名
    const finalReceiverId = receiverId || acceptorId;
    const finalReceiverName = receiverName || acceptorName;
    const finalReceiverAvatar = receiverAvatar || acceptorAvatar;

    console.log('【updateTaskStatus】最终参数：');
    console.log('  - finalReceiverId:', finalReceiverId);
    console.log('  - finalReceiverName:', finalReceiverName);
    console.log('  - finalReceiverAvatar:', finalReceiverAvatar);

    if (status === 'processing' && finalReceiverId) {
      updateData.receiver_id = finalReceiverId;
      updateData.receiver_name = finalReceiverName;
      updateData.receiver_avatar = finalReceiverAvatar;
      updateData.accept_time = new Date().toISOString(); // 记录接单时间
      
      console.log('【updateTaskStatus】添加接单者信息到更新数据');
    } else {
      console.log('【updateTaskStatus】不满足添加接单者信息的条件');
      console.log('  - status === "processing":', status === 'processing');
      console.log('  - finalReceiverId存在:', !!finalReceiverId);
    }

    console.log('【updateTaskStatus】更新数据：', updateData);
    await collection.doc(taskId).update(updateData);
    console.log('【updateTaskStatus】任务状态更新成功');

    // 当状态变为 'processing' 时，更新收入记录
    if (status === 'processing' && finalReceiverId) {
      try {
        console.log('【updateTaskStatus】开始更新收入记录:', {
          taskId: taskId,
          receiverId: finalReceiverId
        });
        
        // 直接更新收入记录
        const incomeUpdateResult = await db.collection('task_income_records')
          .where({ task_id: taskId })
          .update({
            receiver_id: finalReceiverId,
            status: 'processing',
            accept_time: Date.now()
          });
        
        console.log('【updateTaskStatus】收入记录更新结果:', incomeUpdateResult);
        
        if (incomeUpdateResult.updated > 0) {
          console.log('【updateTaskStatus】收入记录更新成功');
        } else {
          console.log('【updateTaskStatus】未找到对应的收入记录');
        }
      } catch (incomeError) {
        console.error('【updateTaskStatus】收入记录更新失败:', incomeError);
      }
    }

    // 如果任务提交验收，记录提交时间
    if (status === 'pending_review') {
      updateData.submit_time = new Date().toISOString();
      console.log('【updateTaskStatus】记录任务提交验收时间');
    }

    // 生成任务通知消息
    if (status === 'processing' && finalReceiverId) {
      try {
        // 1. 为任务发布者生成通知：任务被领取
        await uniCloud.callFunction({
          name: 'createTaskNotification',
          data: {
            userId: task.publisher_id,
            taskId: taskId,
            taskTitle: task.title || task.type,
            status: 'accepted', // 使用 accepted 状态来生成通知
            actionUserId: finalReceiverId,
            actionUserNickname: finalReceiverName
          }
        });
        console.log('【updateTaskStatus】任务发布者通知生成成功');

        // 2. 为任务接单者生成通知：任务领取成功提醒
        await uniCloud.callFunction({
          name: 'createTaskNotification',
          data: {
            userId: finalReceiverId,
            taskId: taskId,
            taskTitle: task.title || task.type,
            status: 'claimed', // 使用 claimed 状态来生成接单者通知
            actionUserId: finalReceiverId,
            actionUserNickname: finalReceiverName
          }
        });
        console.log('【updateTaskStatus】任务接单者通知生成成功');
      } catch (notificationError) {
        console.error('【updateTaskStatus】通知生成失败:', notificationError);
      }
    }

    // 如果任务提交验收，通知发布者
    if (status === 'pending_review' && finalReceiverId) {
      try {
        await uniCloud.callFunction({
          name: 'createTaskNotification',
          data: {
            userId: task.publisher_id,
            taskId: taskId,
            taskTitle: task.title || task.type,
            status: 'completed', // 使用 completed 状态来生成验收通知
            actionUserId: finalReceiverId,
            actionUserNickname: finalReceiverName
          }
        });
        console.log('【updateTaskStatus】任务验收通知生成成功');
      } catch (notificationError) {
        console.error('【updateTaskStatus】验收通知生成失败:', notificationError);
      }
    }

    return { code: 200, msg: 'Success' };
  } catch (error) {
    console.error('【updateTaskStatus】更新任务状态失败:', error);
    return { code: 500, msg: error.message };
  }
};